﻿using Common.Extension;

namespace DesignModeConsole.行为型.策略模式;

// 对于策略类是无状态的，不包含成员变量，只是纯粹的算法实现，那么这样子的策略对象就是可以被共享使用的，不需要每次调用的时候创建新的策略对象，
// 所以这个时候我们就可以使用工厂类的实现方式，事先创建好每个策略对象，缓存到工厂类中，用的时候直接返回

/// <summary>
/// 不包含状态的策略创建
/// </summary>
public class NoStateObjectStrategyFactory
{
    private static readonly Dictionary<string, IStrategy> _strategies = new Dictionary<string, IStrategy>();

    static NoStateObjectStrategyFactory()
    {
        _strategies.Add("A", new ConcreteStrategyA());
        _strategies.Add("B", new ConcreteStrategyB());
    }

    public static IStrategy GetStrategy(string type)
    {
        if (type.IsNullOrWhiteSpace())
            throw new ArgumentException("参数错误");
        return _strategies.GetValueOrDefault(type);
    }
}

/// <summary>
/// 包含状态对象的策略工厂
/// </summary>
public class ContainStateObjectStrategyFactory
{
    public static IStrategy GetStrategy(string type)
    {
        if (type.IsNullOrWhiteSpace())
            throw new ArgumentException("参数错误");
        if (type == "A")
        {
            return new ConcreteStrategyA();
        }
        else if (type == "B")
        {
            return new ConcreteStrategyB();
        }

        return default;
    }
}

/// <summary>
/// 反射创建
/// </summary>
public class ReflectStrategyFactory
{
    private static readonly Dictionary<string, Type> _strategies = new Dictionary<string, Type>();

    static ReflectStrategyFactory()
    {
        _strategies.Add("A", typeof(ConcreteStrategyA));
        _strategies.Add("B", typeof(ConcreteStrategyB));
    }

    public static IStrategy GetStrategy(string type)
    {
        if (type.IsNullOrWhiteSpace())
            throw new ArgumentException("参数错误");

        var flag = _strategies.TryGetValue(type, out var strategiesType);
        if (!flag)
            throw new ArgumentException("参数无效");

        return Activator.CreateInstance(strategiesType) as IStrategy;
    }
}